<?php

namespace app\admin\controller;

use app\admin\model\GroupUser;
use app\common\controller\AdminController;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\Request;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="用户管理")
 */
class User extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new GroupUser();
        $this->sort  = ['sort' => 'desc', 'id' => 'desc'];
        //        $this->validateClass = ''; // 后期加上这个验证器
        $this->joinTable = 'userAuth';
        $this->each      = true;
    }

    /**
     * @param $list
     * @return mixed
     */
    public function each($list): mixed
    {
        return $list->each(function ($item)
        {
            $item->auth_ids = implode(',', $item->userAuth->column('group_auth_id'));
        });
    }

    /**
     * @NodeAnnotation(title="添加")
     */
    public function add(Request $request): Json
    {
        $this->checkPost();
        $post    = $request->post();
        $authIds = $request->post('auth_ids', '');
        $authIds = explode(',', $authIds);
        //        $this->validate($post, 'add');
        if (empty($post['password'])) $post['password'] = '123456';
        $post['password'] = password($post['password']);
        $post['group_id'] = $this->groupId;
        $save             = true;
        try {
            $this->model->transaction(function () use ($post, $authIds, &$save)
            {
                $save = $this->model->save($post);
                if ($save) {
                    $userAuth = array_map(function ($authId)
                    {
                        return ['group_user_id' => $this->model->id, 'group_auth_id' => $authId];
                    }, $authIds);
                    $this->model->userAuth()->saveAll($userAuth);
                }
            });
        } catch (\Exception $e) {
            $this->error('保存失败');
        }
        if ($save) return $this->success('保存成功');
        return $this->error('保存失败');
    }

    /**
     * @NodeAnnotation (title="编辑")
     */
    public function edit(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'id' => 'require|integer'
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) return $this->error('数据不存在！');
        $authIds = !empty($post['auth_id']) ? $post['auth_id'] : '';
        if ($this->uid != $row->id && !$this->userInfo['is_super']) return $this->error('无权限操作');
        if (empty($post['password'])) $post['password'] = '123456';
        $post['password'] = password($post['password']);
        $this->sceneValidate($post, 'edit');
        try {
            $this->model->transaction(function () use ($post, $authIds, $row, &$save)
            {
                $save = $row->save($post);
                if ($save && $authIds) {
                    $authIds = explode(',', $authIds);
                    $this->model->userAuth()->where('group_user_id', $row->id)->delete(true);
                    $userAuth = array_map(function ($authId) use ($row)
                    {
                        return ['group_user_id' => $row->id, 'group_auth_id' => $authId];
                    }, $authIds);
                    $this->model->userAuth()->saveAll($userAuth);
                }
            });
        } catch (\Exception $e) {
            return $this->error('编辑失败');
        }
        return $this->success('编辑成功');
    }

}